package com.cby.android.sample.ext

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.*
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.cby.android.olive.ext.showToast
import com.cby.android.olive.ext.start
import com.cby.android.sample.MainActivity
import com.cby.android.sample.activities.WeatherActivity
import com.cby.android.sample.constant.Constant
import com.cby.android.sample.intent.WeatherIntent
import com.cby.android.sample.utils.LocationUtils.getAddress
import kotlinx.coroutines.launch

/**
 * @description: MainActivityExt
 * @author: ChenBaoYang
 * @createDate: 2022/5/6 4:54 下午
 */
val MainActivity.locationManager: LocationManager
    get() {
        return getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }

val MainActivity.locationProvider: String
    get() {
        val providers: List<String> = locationManager.getProviders(true)
        when {
            providers.contains(LocationManager.GPS_PROVIDER) -> {
                //如果是GPS
                return LocationManager.GPS_PROVIDER
                //Log.v("TAG", "定位方式GPS")
            }
            providers.contains(LocationManager.NETWORK_PROVIDER) -> {
                //如果是Network
                return LocationManager.NETWORK_PROVIDER
                //Log.v("TAG", "定位方式Network")
            }
            else -> {
                Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show()
                return ""
            }
        }
    }



@SuppressLint("MissingPermission")
fun MainActivity.initLocationAboveM() {
    //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
    if (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)
        && hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
    ) {

        //3.获取上次的位置，一般第一次运行，此值为null
        val location: Location? = locationManager.getLastKnownLocation(locationProvider)
        if (location != null) {
            Log.v(
                "TAG",
                "获取上次的位置-经纬度：" + location.longitude
                    .toString() + "   " + location.latitude
            )
            val address = getAddress(this, location)
            if (!address.isNullOrEmpty()) {
                cityName = address[0].locality
                provinceName = address[0].adminArea
                countryName = address[0].countryName
                longitude = address[0].longitude
                latitude = address[0].latitude
            }
        } else {
            //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
            locationManager.requestLocationUpdates(
                locationProvider,
                3000, 1f, locationListener
            )
        }
    } else {
        //请求权限
        ActivityCompat.requestPermissions(
            this, arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ), locationCodeReq
        )
    }
}

@SuppressLint("MissingPermission")
fun MainActivity.initLocationLowM() {

    val location = locationManager.getLastKnownLocation(locationProvider)
    if (location != null) {
        Log.v(
            "TAG",
            "获取上次的位置-经纬度：" + location.longitude + "   " + location.latitude
        )
        val address = getAddress(this, location)
        if (!address.isNullOrEmpty()) {
            cityName = address[0].locality
            provinceName = address[0].adminArea
            countryName = address[0].countryName
            longitude = address[0].longitude
            latitude = address[0].latitude
        }
    } else {
        //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
        locationManager.requestLocationUpdates(locationProvider, 3000, 1f, locationListener)
    }
}


fun MainActivity.requestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {

    if (requestCode == locationCodeReq) {
        initLocationAboveM()
    }
}


fun MainActivity.hasPermission(permissionName: String) =
    ActivityCompat.checkSelfPermission(
        this,
        permissionName
    ) == PackageManager.PERMISSION_GRANTED


val MainActivity.locationListener: LocationListener
    get() = object : LocationListener {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        override fun onStatusChanged(
            provider: String,
            status: Int,
            extras: Bundle
        ) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        override fun onProviderEnabled(provider: String) {}

        // Provider被disable时触发此函数，比如GPS被关闭
        override fun onProviderDisabled(provider: String) {}

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        override fun onLocationChanged(location: Location) {
            //如果位置发生变化，重新显示地理位置经纬度
            showToast(
                location.longitude.toString() + " " +
                        location.latitude + ""
            )
            Log.v(
                "TAG",
                "监视地理位置变化-经纬度：" + location.longitude + "   " + location.latitude
            )
        }
    }

fun MainActivity.openWeather() {
    val data = Bundle()
    data.putString(Constant.KEY_PROVINCE_NAME, provinceName)
    data.putString(Constant.KEY_CITY_NAME, cityName)
    val location = "$longitude,$latitude"
    data.putString(Constant.KEY_LOCATION, location)
    start(WeatherActivity::class.java, data)
}


